﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using com.google.zxing.qrcode;
using com.google.zxing;
using com.google.zxing.common;

namespace qrcode
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
           
        }
        private void encode_qr()
        {
            QRCodeWriter writer = new QRCodeWriter();
            Hashtable hints = new Hashtable();

            hints.Add(EncodeHintType.ERROR_CORRECTION, com.google.zxing.qrcode.decoder.ErrorCorrectionLevel.L);
            hints.Add("Version", "7");

            //Change to UTF-8
            byte[] b = { 0xEF, 0xBB, 0xBF };
            System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
            string s = encoding.GetString(b);
            s += textBox1.Text;
            //End

            ByteMatrix byteIMGNew = writer.encode(s, BarcodeFormat.QR_CODE, 350, 350, hints);

            sbyte[][] imgNew = byteIMGNew.Array;
            Bitmap bmp1 = new Bitmap(byteIMGNew.Width, byteIMGNew.Height);
            Graphics g1 = Graphics.FromImage(bmp1);
            g1.Clear(Color.White);
            for (int i = 0; i <= imgNew.Length - 1; i++)
            {
                for (int j = 0; j <= imgNew[i].Length - 1; j++)
                {
                    if (imgNew[j][i] == 0)
                    {
                        g1.FillRectangle(Brushes.Black, i, j, 1, 1);
                    }
                    else
                    {
                        g1.FillRectangle(Brushes.White, i, j, 1, 1);
                    }
                }
            }
            bmp1.Save("D:\\QREncode.jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
        }
        private void decode_qr()
        {
            com.google.zxing.qrcode.decoder.Decoder objDecoder = new com.google.zxing.qrcode.decoder.Decoder();
            Bitmap bitmap = new Bitmap("D:\\QREncode.jpg");
            com.google.zxing.LuminanceSource source = new RGBLuminanceSource(bitmap, bitmap.Width, bitmap.Height);
            var binarizer = new HybridBinarizer(source);
            var binBitmap = new BinaryBitmap(binarizer);
            QRCodeReader qrCodeReader = new QRCodeReader();
            string str = qrCodeReader.decode(binBitmap).Text;
            label1.Text = str;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            encode_qr();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            decode_qr();
        }
    }
}